package per.kongtouxu.controller;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import per.kongtouxu.domain.dto.JsonDto;
import per.kongtouxu.domain.pojo.*;
import per.kongtouxu.domain.vo.V_FileInfo;
import per.kongtouxu.service.FileInfoService;
import per.kongtouxu.service.Impl.UserServiceImpl;
import per.kongtouxu.service.UserScoreIoService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/fileInfo")
public class FileInfoController {
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserScoreIoService userScoreIoService;
    //分页查询
    @RequestMapping("/pageFind")
    public @ResponseBody PageBean<V_FileInfo> pageFind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        String fileName = req.getParameter("FileName");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");
        String userId = req.getParameter("userId");

        PageBean<V_FileInfo> pageBean =null;
        if(userId.equals("0")){
            pageBean = this.fileInfoService.pageFind(fileName, startTime, endTime, null,Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        }else {
            //2.查询service
            pageBean = this.fileInfoService.pageFind(fileName, startTime, endTime, Integer.parseInt(userId),Integer.parseInt(currentPage), Integer.parseInt(pageSize));
        }
      
        System.out.println(pageBean);
        //3.返回JSON
        return pageBean;
    }
    //文件上传
    @RequestMapping("/upload")
    public @ResponseBody JsonDto uploader(MultipartFile file,HttpServletRequest request) throws IOException {
        System.out.println(file.getName()); // file - 变量的名称
        System.out.println(file.getOriginalFilename()); // 文件名称
        System.out.println(file.getSize()); // 文件大小
        System.out.println(file.getInputStream()); // 文件流
        System.out.println("springMVC文件上传.....");
        //使用fileupload组件完成文件上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断,该路径是否存在
        File saveFile = new File(path);
        if(!saveFile.exists()){
            saveFile.mkdir();
        }
        //上传文件项获取
        //获取文件名
        String filename = file.getOriginalFilename();
        //获取文件名后缀
        String[] split = filename.split("\\.");
        String suffix = split[split.length-1];
        //查询文件类型
        FileType fileType = fileInfoService.findFileTypeBySuffix(suffix);
        //把文件的名字设置唯一值,uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename=uuid+"_"+filename;
        //获取积分
        Integer typeScore = fileType.getTypeScore();
        //完成文件上传
        System.out.println("文件保存的路径......."+path);
        file.transferTo(new File(path,filename));
        //返回JSON对象
        JsonDto dto = new JsonDto();
        dto.setMessage("文件上传成功");
        dto.getDatas().put("filepath",path+"\\"+filename);
        dto.getDatas().put("filesize",file.getSize());
        dto.getDatas().put("fileType",fileType.getFtId());
        dto.getDatas().put("typeScore",typeScore);
        return dto;
    }
    //文件下载
    @RequestMapping("/download")
    public void download( HttpServletResponse response,String filename,String path) throws IOException {
//        String filename = "mele.jpg";
//        String path = "D:\\Professional_SoftWare\\01Java_SoftWare\\01IDEA\\02IDEA_Project\\Demo04_NEW_START\\Demo17FileManage\\Demo02FileManageFront\\src\\main\\webapp\\uploads\\0fb47fbef6b34c3289b82a3024cdbfa1_Mole.jpg";
        System.out.println("filename:"+filename);
        System.out.println("path:"+path);
        // 设置下载的文件的文件名
        response.addHeader("Content-Disposition", "attachment;filename="
                + URLEncoder.encode(filename,"UTF-8"));
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        // 将文件发送出去
        FileUtils.copyFile(new File(path), response.getOutputStream());
    }
    //文件上传记录登记
    @RequestMapping(value = "/fileRowUpload", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody JsonDto fileRowUpload(@RequestBody FileInfo fileInfo,@RequestParam Integer typeScore) {
        System.out.println("FileInfo:"+fileInfo);
        System.out.println("typeScore:"+typeScore+"   "+"userId:"+fileInfo.getUserId());
        fileInfoService.add(fileInfo,typeScore);

        JsonDto dto = new JsonDto();
        dto.setMessage("文件上传成功");
        return dto;
    }

    //用户文件下载
    @RequestMapping("/userDownload")
    public @ResponseBody JsonDto userDownload( Integer fileId,Integer fileScore,Integer userId,String downLoadFileName){
        System.out.println("fileId:"+fileId+"fileScore:"+fileScore+"userId:"+userId+"downLoadFileName:"+downLoadFileName);
        //1.判断用户是否有积分下载文件
        User user = userService.findUserById(userId);
        //2.判断文件是否下载过，或者是上传的
        UserScoreIo userScoreIo = userScoreIoService.findByFileIdAndUserId(fileId, userId);
        //2.1查询文件信息
        FileInfo fileInfo = fileInfoService.findFileById(fileId);
        //2.2合成下载路径
        String downPath = "fileInfo/download?filename="+downLoadFileName+"&path="+fileInfo.getSavePath();
        HashMap<String, Object> map = new HashMap<>();
        if (userScoreIo != null){
            //文件已经是上传或者是下载过了
            map.put("downLoadPath",downPath);
            return new JsonDto(1,"",null,map);
        }else {
            if(user.getUserScore() >= fileScore){
                //2.用户有积分
                //2.3扣除分数
                userService.updateScoreByUserId(userId, (~(fileScore - 1)));
                //2.4添加流水
                UserScoreIo ScoreIo = new UserScoreIo();
                ScoreIo.setFileId(fileId);
                ScoreIo.setUserId(userId);
                ScoreIo.setScore(fileScore);
                ScoreIo.setScoreState("减少");
                userScoreIoService.add(ScoreIo);
                //2.5返回信息
                map.put("downLoadPath",downPath);
                return new JsonDto(1,"",null,map);
            }else {
                //3.用户无积分
                return new JsonDto(0,"您没有足够的积分",null,null);
            }
        }
    }
}
